#include "libraryEngine.h"

namespace LIB {

void load(std::vector<songData> &LIBRARY)
{
	// creates a file stream with the library file
	std::fstream library_stream (LIB::LOCATION, std::ios::in);

	if (library_stream.is_open()) { // stream opens correctly
		while (!library_stream.eof()) {
			songData temp; // temp songData container to be pushed into LIBRARY

			// name, artist and location are read from the first three values
			std::getline(library_stream, temp.name, LIB::FIELD_SPLITTER);
			std::getline(library_stream, temp.artist, LIB::FIELD_SPLITTER);
			std::getline(library_stream, temp.location, LIB::FIELD_SPLITTER);

			// tags are taken from the rest of the line
			std::string all_tags;
			std::getline(library_stream, all_tags, LIB::RECORD_SPLITTER);

			// all_tags is split into individual tags and each is pushed to temp.tags
			std::stringstream ss(all_tags);
			std::string buffer;
			while (std::getline(ss, buffer, LIB::FIELD_SPLITTER))
				temp.tags.push_back(buffer);

			// temp is pushed to LIBRARY
			LIBRARY.push_back(temp);
		};
	} else { // stream does not open
		std::cout << "Could not open library.\n";
	};

	library_stream.close();
};

void save(const std::vector<songData> &LIBRARY)
{
	// creates a file stream to write to
	std::fstream library_stream (LIB::LOCATION, std::ios::out);

	if (library_stream.is_open()) {
		std::vector<songData>::const_iterator itr;
		for (itr = LIBRARY.begin(); itr != LIBRARY.end(); itr++) { // for each library item
			// writes name, artist and location first
			library_stream << itr->name << LIB::FIELD_SPLITTER;
			library_stream << itr->artist << LIB::FIELD_SPLITTER;
			library_stream << itr->location << LIB::FIELD_SPLITTER;

			// writes the tags one at a time separated by LIB::FIELD_SPLITTER
			std::vector<std::string>::const_iterator tag_itr;
			for (tag_itr = itr->tags.begin(); tag_itr != itr->tags.end(); tag_itr++) {
				library_stream << *tag_itr;

				// outputs LIB::FIELD_SPLITTER or LIB::RECORD_SPLITTER depending on tag
				if (tag_itr+1 == itr->tags.end()) { // if it's the last tag in the list
					if (itr+1 != LIBRARY.end()) { // if it isn't the last record in LIBRARY
						library_stream << LIB::RECORD_SPLITTER;
					};
				} else { // write a LIB::FIELD_SPLITTER -- there are more tags to come for this record
					library_stream << LIB::FIELD_SPLITTER;
				};
			};
		};
	} else {
		std::cout << "Could not write library.\n";
	};

	library_stream.close();
};

};